import { defineStore } from "pinia";
import { reEmail } from "@/global";
import { AxiosResponse } from 'axios';
import { PersistedStateOptions } from 'pinia-plugin-persistedstate';
import request from '@/untils/request';
import router from '@/router';
import { ElMessage } from "element-plus";

const userStore: any = defineStore('user', {
	state: () => {
		return {
			id: 0 as number,
			name: '' as string,
			mail: '' as string,
			password: '' as string,
			phone: '' as string,
			success: false as boolean,
			boxState: false as boolean,
		}
	},
	persist: {
		enabled: true,
		strategies: [
			{
				key: 'myuser',
				storage: localStorage,
			}
		],
	} as PersistedStateOptions,
	actions: {
		async doLogin() {
			if (this.mail.trim() === '' || this.password.trim() === '') {
				ElMessage.error('不能为空');
				return;
			}
			if (reEmail.test(this.mail) === false) {
				ElMessage.error('邮箱格式错误');
				return;
			}
			request.post('/dologin', {
				mail: this.mail,
				password: this.password,
			}).then((res: AxiosResponse) => {
				if (res.data.code === 500) {
					ElMessage.error('账号或密码错误');
					return;
				} else ElMessage.success('登录成功');
				this.success = true;
				this.id = res.data.user.id;
				this.name = res.data.user.name;
				this.mail = res.data.user.mail;
				this.phone = res.data.user.phone;
				setTimeout(() => router.push('/edit'), 30);
			}).then(() => {
				this.password = '';
			}).catch(() => ElMessage.error('网络错误'));
		},
		async doRegister() {
			if (this.mail.trim() === '' || this.password.trim() === '') {
				ElMessage.error('不能为空');
				return;
			}
			if (this.phone.trim() === '' || this.name.trim() === '') {
				ElMessage.error('不能为空');
				return;
			}
			if (reEmail.test(this.mail) === false) {
				ElMessage.error('邮箱格式错误');
				return;
			}
			if (this.phone.toString().length != 11) {
				ElMessage.error('手机号码格式错误');
				return;
			}
			request.post('doregister', {
				name: this.name,
				mail: this.mail,
				password: this.password,
				phone_number: this.phone
			}).then((res) => {
				if (res.data.code === 500) {
					ElMessage.error(res.data.message);
					return;
				} else ElMessage.success(res.data.message);
				this.success = true;
				this.id = res.data.user_id;
				this.password = '';
				setTimeout(() => router.push('/edit'), 30);
			}).catch(() => {
				ElMessage.error('网络错误');
			});
		},
		clearUser() {
			this.id = 0;
			this.name = '';
			this.mail = '';
			this.password = '';
			this.phone = '';
			this.success = false;
		}
	},
});

export default userStore;
